package cn.net.isir.controller.miniprogram;

import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import cn.net.isir.common.RequestObject;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.pay.alipay.AlipayAPI;
import cn.net.isir.entity.AlipayMinipUserinfo;
import cn.net.isir.service2.AlipayMinipUserinfoService;
import cn.net.isir.utils.RequestUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxubo
 * @filename AlipayUserController.java
 * @package cn.net.isir.controller.miniprogram
 * @email lxb@isir.net.cn
 * @date 2018/08/28
 * @comment
 * @since 1.7
 */
@RestController("minipAlipayUserController")
@RequestMapping(value = "/minip/alipay")
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {Exception.class, RuntimeException.class})
public class AlipayUserController {

    @Resource
    private AlipayMinipUserinfoService alipayMinipUserinfoService;

    @RequestMapping(value = "/userid", method = RequestMethod.GET)
    public ResultObject getUserId(RequestObject obj) {
        //声明返回值
        ResultObject ro;
        //声明参数解码后的储存变量
        Map<String, Object> reqParamMap = new HashMap<>();
        //需要检查的字段名
        String[] columns = new String[]{"authCode"};
        //检查失败则返回缺失的字段提示
        if ((ro = RequestUtils.parametersCheck(obj, reqParamMap, columns)).getResult() != 200) {
            return ro;
        }
        String authCode = String.valueOf(reqParamMap.get("authCode"));
        //获取userid
        AlipaySystemOauthTokenResponse resp1 =
                AlipayAPI.alipaySystemOauthToken("authorization_code", authCode, null);
        if (resp1 == null) {
            return new ResultObject(500, "获取userId失败", null);
        }
        AlipayMinipUserinfo userinfo = new AlipayMinipUserinfo();
        userinfo.setUser_id(resp1.getUserId());
        userinfo = alipayMinipUserinfoService.selectOne(userinfo);
        //用户是否存在(因为第二次（插入/新增的时候，无法通过判断userinfo是否为null来决定操作插入/新增）)
        boolean isExistUserInfo = true;
        if (userinfo == null) {
            userinfo = new AlipayMinipUserinfo();
            isExistUserInfo = false;
        }
        userinfo.setUser_id(resp1.getUserId());
        userinfo.setAccess_token(resp1.getAccessToken());
        userinfo.setExpires_in(resp1.getExpiresIn());
        userinfo.setRefresh_token(resp1.getRefreshToken());
        userinfo.setRe_expires_in(resp1.getReExpiresIn());

        //获取会员信息
        AlipayUserInfoShareResponse resp2 =
                AlipayAPI.alipayUserInfoShare(resp1.getAccessToken());
        //code=10000
        if (resp2 != null) {
            //获取用户信息
            userinfo.setAvatar(resp2.getAvatar());
            userinfo.setProvince(resp2.getProvince());
            userinfo.setCity(resp2.getCity());
            userinfo.setNick_name(resp2.getNickName());
            userinfo.setIs_student_certified(resp2.getIsStudentCertified());
            userinfo.setUser_type(resp2.getUserType());
            userinfo.setUser_status(resp2.getUserStatus());
            userinfo.setIs_certified(resp2.getIsCertified());
            userinfo.setGender(resp2.getGender());
            userinfo.setMobile(resp2.getMobile());
        }
        if (isExistUserInfo) {
            alipayMinipUserinfoService.update(userinfo);
        } else {
            alipayMinipUserinfoService.insert(userinfo);
        }
        return new ResultObject(200, "success", resp1.getUserId());
    }

    /**
     * 微信用户信息
     *
     * @param obj 请求参数
     * @return 结果
     */
    @RequestMapping(method = RequestMethod.GET, value = "/info")
    public ResultObject getWxUserInfo(RequestObject obj, HttpServletRequest request, HttpServletResponse response) {
        //声明返回值
        ResultObject ro;
        //声明参数解码后的储存变量
        Map<String, Object> reqParamMap = new HashMap<>();
        //需要检查的字段名
        String[] columns = new String[]{"userid"};
        //检查失败则返回缺失的字段提示
        if ((ro = RequestUtils.parametersCheck(obj, reqParamMap, columns)).getResult() != 200) {
            return ro;
        }
        String userid = String.valueOf(reqParamMap.get("userid"));
        AlipayMinipUserinfo userInfo = new AlipayMinipUserinfo();
        userInfo.setUser_id(userid);
        userInfo = alipayMinipUserinfoService.selectOne(userInfo);
        if (userInfo != null) {
            AlipayMinipUserinfo userInfo2 = new AlipayMinipUserinfo();
            userInfo2.setUser_id(userInfo.getUser_id());
            userInfo2.setAvatar(userInfo.getAvatar());
            userInfo2.setNick_name(userInfo.getNick_name());
            return new ResultObject(200, "success", userInfo);
        }
        return new ResultObject(500, "没有此用户", null);
    }


    public static void main(String[] args) {
//        new WxInterfaceService().getUnionid("YAJUUVHaAerz4kjH1LMshDQifFaUvQdxOPCjVbdsvxmu5lEdgLQrthWlT1CKaF+EJKlQhM4sYby7t+1RYJb//yGYWrFklpcT0IKVMyrcFCvIaOjr8NIkPOLAhHQK7Fv0ZyahmuVQLhnizAvx5euuF3meK8bRb7BVS8I3lcT0l9axz/Y3daiAYR9zP7KhA9eU0FffRoIZS8UzWyD6FXfixQ==","jU6XGD4Kqaubk83EMUxa4g==","jU6XGD4Kqaubk83EMUxa4g==");
    }
}
